import time

import jwt
from flask import request, g

from config import JWT_SECRET, TokenExp


class JwtClass(object):
    """
    Jwt 登录权限验证
    """

    @staticmethod
    def check_auth():
        auth = request.headers.get("Authorization")
        g.userinfo = {}
        g.code = 400
        if auth and auth.startswith('Bearer '):
            token = auth[7:]
            try:
                "判断token的校验结果"
                payload = jwt.decode(token, JWT_SECRET, algorithms=['HS256'])
                isTrue = JwtClass.check_token(payload)
                if not isTrue:
                    raise jwt.exceptions.ExpiredSignatureError
                g.userinfo = payload
                g.code = 200
                g.userinfo = payload
            except Exception:
                g.code = 1001
        return g.code

    @staticmethod
    def create_token(payload):
        headers = {
            'typ': 'jwt',
            'alg': 'HS256'
        }
        payload["exp"] = int(time.time()) + 60 * TokenExp
        params = {
            "payload": payload,
            "key": JWT_SECRET,
            "algorithm": "HS256",
            "headers": headers
        }
        result = jwt.encode(**params)
        return result, payload["exp"]

    # 检查数据库中的token
    @staticmethod
    def check_token(userinfo):
        # TODO 检查数据库中的token 比如 修改密码或者禁用用户后 需要及时退出登录
        # 主动过期
        # mysqlObj = MysqlClass(DBInfo["default"])
        # expired = mysqlObj.getField(table_name,
        # 1"expired", f"id={payload['uid']}")
        # if expired == 0 or int(time.time()) > expired:
        #     raise jwt.exceptions.ExpiredSignatureError
        return True
